// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:audio_waveforms/audio_waveforms.dart';
import 'package:common/common.dart';
import 'package:common/image/image_tools.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:miaowu/app/module/world/world_audio_publish/water_button.dart';
import 'package:miaowu/app/module/world/world_audio_publish/waveforms_widget.dart';

import '../../../world/audio/recorder/recorder_manager.dart';
import 'pond_publish_audio_logic.dart';
import 'pond_publish_audio_state.dart';

/// @description:
/// @author
/// @date: 2025-01-20 09:58:27
class PondPublishAudioPage extends StatefulWidget {
  const PondPublishAudioPage({Key? key, required this.onCallBack}) : super(key: key);

  final Function onCallBack;
  @override
  State<PondPublishAudioPage> createState() => _PondPublishAudioPageState();
}

class _PondPublishAudioPageState extends State<PondPublishAudioPage> {
  final PondPublishAudioLogic logic = Get.put(PondPublishAudioLogic());

  final PondPublishAudioState state = Get.find<PondPublishAudioLogic>().state;

  late final RecorderController recorderController;

  String? audioPath;
  bool isRecording = false;
  int audioDuration = 0;
  int maxTime = 120;
  int minlong = 6;

  AudioCardState audioCardState = AudioCardState.initial;

  @override
  void initState() {
    super.initState();

    PermissionUtils.microphone();
    RecorderManager.instance.configRecordParams(minTime: 6, maxTime: 10);
    recorderController = RecorderManager.instance.init();
    RecorderManager.instance.onChangeState = (AudioCardState state, int duration, String fildPath) {
      setState(() {
        audioCardState = state;
        audioPath = fildPath;
        if (state == AudioCardState.recording) {
          isRecording = true;
        } else if (state == AudioCardState.initial) {
          isRecording = false;
          audioPath = null;
        } else if (state == AudioCardState.recordingCompleted) {
          isRecording = false;
        }
      });
    };
    RecorderManager.instance.onCurrentDuration = (int duration) {
      setState(() {
        audioDuration = duration;
      });
    };
  }

  @override
  void dispose() {
    // recorderController.dispose();
    RecorderManager.instance.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Container(
        color: Colors.transparent,
        padding: EdgeInsets.only(
            bottom: MediaQuery.of(context).padding.bottom == 0 ? 10 : (MediaQuery.of(context).padding.bottom - 10)),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            _buildAudioTipsWapper(), // 录音提示文字
            const Spacer(),
            _buildAudioWaveWarpper(context), //  录音波形
            const SizedBox(height: 40),
            _buildAudioButtonsWarpper(),
            Container(
              margin: const EdgeInsets.only(right: 10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Image.asset('assets/app/images/auth/auth_check_n.png', width: 15.w),
                  const SizedBox(width: 3),
                  Text('同步到视界', style: TextStyle(color: Colors.black, fontSize: 13.sp))
                ],
              ),
            ),
            Container(
              height: 51,
              margin: const EdgeInsets.only(left: 20, right: 20, top: 20),
              alignment: Alignment.center,
              decoration: BoxDecoration(color: const Color(0xFF25D4D0), borderRadius: BorderRadius.circular(25)),
              child: Text('确认发布', style: TextStyle(color: Colors.white, fontSize: 16.sp, fontWeight: FontWeight.w600)),
            ),
            SizedBox(height: AppScreen.safeAreaPaddingBottom)
          ],
        ),
      ),
    );
  }

  Widget _buildAudioButtonsWarpper() {
    return Container(
      color: Colors.transparent,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          if (isRecording == false && audioPath != null) _buildAudioDeleteButtonWarpper(), // 删除录音按钮
          _buildRecordButtonWarpper(),
          if (isRecording == false && audioPath != null)
            const SizedBox(), // _buildAudioFinishButtonWarpper(), // 录音完成按钮
        ],
      ),
    );
  }

  GestureDetector _buildRecordButtonWarpper() {
    return GestureDetector(
      onTap: () {
        RecorderManager.instance.startOrStopRecording();
      },
      child: Container(
          padding: const EdgeInsets.only(bottom: 10),
          child: Column(
            children: [
              Stack(
                children: [
                  Container(
                      width: 100,
                      height: 100,
                      color: Colors.transparent,
                      child: audioCardState == AudioCardState.recording
                          ? const ACEWaterButton(color: Color(0xFFE9FAFA))
                          : const SizedBox()),
                  Positioned.fill(
                    child: Center(
                      child: Image.asset(
                          audioCardState == AudioCardState.recording
                              ? 'assets/app/images/world/audio_start_ing_icon.png'
                              : 'assets/app/images/world/audio_start_icon.png',
                          width: 80.w),
                    ),
                  ),
                  if (audioCardState == AudioCardState.recording)
                    Positioned.fill(
                        top: 35.h,
                        child: Center(
                            child: Text(
                          '${audioDuration}s',
                          style: TextStyle(color: Colors.white, fontSize: 13.sp, fontWeight: FontWeight.bold),
                        ))),
                ],
              ),
              Center(
                  child: Text(
                audioCardState == AudioCardState.recording ? '录制中' : '点击录制',
                style: TextStyle(color: Colors.black, fontSize: 16.sp, fontWeight: FontWeight.bold),
              ))
            ],
          )),
    );
  }

  GestureDetector _buildAudioFinishButtonWarpper() {
    return GestureDetector(
      onTap: () {
        widget.onCallBack(audioPath);
        Get.back();
      },
      child: Container(
          margin: const EdgeInsets.only(right: 10),
          child: Column(
            children: [
              Image.asset('assets/app/images/world/audio_finish_icon.png', width: 36.w),
              const SizedBox(height: 3),
              Text('完成', style: TextStyle(color: Colors.black, fontSize: 13.sp))
            ],
          )),
    );
  }

  GestureDetector _buildAudioDeleteButtonWarpper() {
    return GestureDetector(
      onTap: () {
        RecorderManager.instance.deleteAudioFile(
            audioPath: audioPath ?? '',
            successCallback: () {
              setState(() {
                audioPath = null;
                isRecording = false;
                audioCardState = AudioCardState.initial;
              });
            });
      },
      child: Container(
        margin: const EdgeInsets.only(left: 10),
        child: Column(
          children: [
            Image.asset('assets/app/images/world/audio_del_icon.png', width: 36.w),
            const SizedBox(height: 3),
            Text('删除', style: TextStyle(color: Colors.black, fontSize: 13.sp))
          ],
        ),
      ),
    );
  }

  Container _buildAudioWaveWarpper(BuildContext context) {
    return Container(
      // margin: const EdgeInsets.only(bottom: 10),
      child: isRecording == false
          ? (audioPath == null
              ? Image.asset('assets/app/images/world/audio_waveform_ing_2.png', width: 186.w)
              : WaveformsWidget(audioPath: audioPath ?? ''))
          : AudioWaveforms(
              enableGesture: true,
              size: Size(MediaQuery.of(context).size.width / 3 * 2, 100),
              recorderController: recorderController,
              waveStyle: const WaveStyle(waveColor: Color(0xFF25D4D0), extendWaveform: true, showMiddleLine: true),
              decoration: BoxDecoration(borderRadius: BorderRadius.circular(12.0), color: Colors.transparent),
              padding: const EdgeInsets.only(left: 18),
              margin: const EdgeInsets.symmetric(horizontal: 15),
            ),
    );
  }

  Container _buildAudioTipsWapper() {
    return Container(
      height: 90,
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      margin: EdgeInsets.only(bottom: 30.h),
      child: Stack(
        children: [
          Image.asset('assets/app/images/pond/pond_audio_tips_bg.png'),
          Container(
            padding: EdgeInsets.only(top: 28.h, left: 20),
            alignment: Alignment.center,
            child: Row(
              children: [
                Expanded(
                  child: Text('您可以轻哼几句歌~啦啦啦，我是卖报的小行您可以轻哼几句歌~啦啦啦，我是卖报的小行',
                      maxLines: 2, style: TextStyle(color: Colors.black, fontSize: 12.sp)),
                ),
                Container(
                  alignment: Alignment.center,
                  padding: const EdgeInsets.only(right: 15),
                  child:
                      Text.rich(TextSpan(style: TextStyle(fontSize: 12.sp, color: const Color(0xFF404A94)), children: [
                    WidgetSpan(
                        alignment: PlaceholderAlignment.middle,
                        child: Padding(
                          padding: const EdgeInsets.only(right: 5),
                          child: Image.asset('assets/app/images/pond/pond_check_icon.png', width: 14.5),
                        )),
                    const TextSpan(text: '换一换'),
                  ])),
                )
              ],
            ),
          )
        ],
      ),
    );
  }
}
